//
//  CAAddingPurifierVC.m
//  CleanerAir_Project
//
//  Created by 车浩 on 16/8/25.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "CAAddingPurifierVC.h"
#import "YLProgressBar.h"
#import "MMWMiotLink.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "MMWMiotLinkWebService.h"
#import "LogInModel.h" 
#import "EquipmentModel.h"

@interface CAAddingPurifierVC (){

    NSString *_cuid;
    
    BOOL _isConfiguration;
    
    int i;
    int k;//这个控制流程
    float sleep;
}

@property (nonatomic, strong) IBOutlet YLProgressBar  *progressBarRoundedFat;

@property (weak, nonatomic) IBOutlet UILabel *wifiNameLabel;

@property (weak, nonatomic) IBOutlet UITextField *wifiPasswordLabel;

@property (weak, nonatomic) IBOutlet UITextField *equipmentNameLabel;

@property (weak, nonatomic) IBOutlet UIButton *configurationBtn;

@property (weak, nonatomic) IBOutlet UIImageView *transparentView;

@property (strong ,nonatomic) EquipmentModel *model;

@end

@implementation CAAddingPurifierVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isConfiguration = NO;
    i = 0;
    k = 60;
    sleep = 0.5;
    _cuid = [LoginSingleton sharedLoginSingleton].cuid;
    
    self.wifiNameLabel.text = [self getWifiInfo][@"SSID"];
    
    [self initRoundedFatProgressBar];
    
    self.configurationBtn.tag = 100;//配置100  取消配置101
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 15, 50, 20)];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(popViewController) forControlEvents:UIControlEventTouchUpInside];
    //    [leftButton setBackgroundImage:[UIImage imageNamed:@"navbtn.png"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;

    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)popViewController{
    
    if (_isConfiguration) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否要停止配置？" preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        [alert addAction:okAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
//            [self.navigationController popViewControllerAnimated:YES];
        }];

        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
            

        
    }else{
    
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


#pragma mark -- 配置按钮

- (IBAction)configuration:(UIButton *)sender {
    
    if (sender.tag == 100) {
        
        if([self.wifiNameLabel.text isEqualToString:@""]){
            [ShowMessage showCenterViewMessage:@"wifi名字不能为空!"];
            return;
        }else if([self.wifiPasswordLabel.text isEqualToString:@""]){
            [ShowMessage showCenterViewMessage:@"wifi密码不能为空!"];
            return;
        }else if ([self.equipmentNameLabel.text isEqualToString:@""]){
            [ShowMessage showCenterViewMessage:@"设备名称不能为空"];
            return;
        }else {
            
            [self.configurationBtn setTitle:@"取消配置" forState:(UIControlStateNormal)];
            self.equipmentNameLabel.userInteractionEnabled = NO;
            self.wifiPasswordLabel.userInteractionEnabled = NO;
            self.transparentView.hidden = NO;
            self.progressBarRoundedFat.hidden = NO;
            self.configurationBtn.tag = 101;
            
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                for (;  i < 100 ; i++) {
                    
                    if(i >= k){
                        
                        i--;
                    }else{
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            float progress = i / 100.0;
                            [self.progressBarRoundedFat setProgress:progress animated:YES];
                        });
                        [NSThread sleepForTimeInterval:sleep];
                        
                    }
                }
                
            });
            
            _isConfiguration = YES;
            
            [self configurationTheRouter];
        }
        
    }else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否要停止配置？" preferredStyle:UIAlertControllerStyleAlert];
        
        
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.configurationBtn.tag = 100;
            [self.configurationBtn setTitle:@"配置" forState:(UIControlStateNormal)];
            [self endConfiguration];
            
        }];
        
        [alert addAction:okAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}

#pragma mark -- 配置失败
- (void)configurationFailure{
    
    self.transparentView.hidden = YES;
    self.progressBarRoundedFat.hidden = YES;
    self.equipmentNameLabel.userInteractionEnabled = YES;
    self.wifiPasswordLabel.userInteractionEnabled = YES;
    
    i = 100;
    k = 101;
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"槽糕！配置失败了。" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    
}

#pragma mark -- 停止配置
- (void)endConfiguration{
    
    self.transparentView.hidden = YES;
    self.progressBarRoundedFat.hidden = YES;
    self.configurationBtn.userInteractionEnabled = YES;
    self.equipmentNameLabel.userInteractionEnabled = YES;
    self.wifiPasswordLabel.userInteractionEnabled = YES;
    
    i = 100;
    k = 101;
    
    [[MMWMiotLink shareInstence] mmw_MiotLinkStopLink];
}

#pragma mark -- 配置路由  && 配置机器连接路由 && 上传信息到妙恋服务器

- (void)configurationTheRouter{
    
    __weak __typeof(self) weakSelf = self;
    
//    
//    [[MMWMiotLink shareInstence]mmw_apMiotLinkConfig:self.wifiNameLabel.text password:self.wifiPasswordLabel.text time:60 callBack:^(MMWMiotLinkDeviceInfo *device){
//
    [[MMWMiotLink shareInstence]mmw_MiotLinkConfig:self.wifiNameLabel.text password:self.wifiPasswordLabel.text configMode:4 time:60 callBack:^(MMWMiotLinkDeviceInfo *device) {
        
        if (device != nil) {
            
            //进度条
            i = 79;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                float progress = i / 100.0;
                [weakSelf.progressBarRoundedFat setProgress:progress animated:YES];
            });
            k = 80;
            sleep = 0.1;
            NSLog(@"配置路由成功！");

            [MMWMiotLink shareInstence].isOfficialServer = YES;
            //   NSLog(@"%d      %d",[_isOfficialServer isOn],[MMWMiotLink shareInstence].isOfficialServer);
            [[MMWMiotLink shareInstence]mmw_MiotLinkFirstConfig:device userPlatformMode:0 userPlatformURL:@"" userPlatformPort:@"" serial:@"9600" time:40 callBack:^(int resultCode) {
                NSString *code = [NSString stringWithFormat:@"result = %@", @(resultCode)];
                i = 95;
                k = 96;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    float progress = i / 100.0;
                    [weakSelf.progressBarRoundedFat setProgress:progress animated:YES];
                });
                sleep = 0.1;
                
                NSLog(@"配置成功 %@",code);
//      [LogInModel shareStudent].weiDu          [LogInModel shareStudent].jingDu
                if (resultCode == 0) {
                    
                    mmwGetPuByMacHTTPWebService *getPuByMacService = [[mmwGetPuByMacHTTPWebService alloc]initWithCuId:[LoginSingleton sharedLoginSingleton].cuid macCode:device.mac deviceName:self.equipmentNameLabel.text deviceCode:self.QrCode longitude:@"120.621403" latitude:@"30.046915" userdata:@"province:浙江省,city:绍兴市,district:越城区,cityCode:0575,adCode:330602"];
                    
                    getPuByMacService.host = MiotlinkWebServiceStr;
                    [getPuByMacService sendRequestWithSuccess:^(__kindof mmwHTTPBaseWebService *webService, id responseObject) {
                        
                        k = 101;
                        i = 100;
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            float progress = i / 100.0;
                            [weakSelf.progressBarRoundedFat setProgress:progress animated:YES];
                        });
                        NSLog(@"上传成功 success %@ ----- %@",webService,responseObject);
                        
//                        //测试
//                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"success" message:[NSString stringWithFormat:@"%@",responseObject] delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//                        [alert show];
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            
                            if (weakSelf.addingBlock != nil) {
                                weakSelf.addingBlock();
                            }

                        });
                        
                    } failure:^(__kindof mmwHTTPBaseWebService *webService, NSError *error) {
                        NSLog(@"fail %@ ----- %@",webService,error);
                        //测试
//                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"fail" message:[NSString stringWithFormat:@"%@",error.localizedDescription] delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//                        [alert show];
                        
                        [weakSelf configurationFailure];
                        
                    }];
                    
                    
                }else{
                    [weakSelf configurationFailure];
                }
                
            }];
            
        }else{
        
            [weakSelf configurationFailure];
        
        }
        
    }];

}

//获取wifi信息
- (NSDictionary*)getWifiInfo{
    
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    
    if (!wifiInterfaces) {
        return nil;
    }
    
    NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
    
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
        
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
            NSLog(@"network info -> %@", networkInfo);
            
            return networkInfo;
        }
    }
    
    return nil;
}

#pragma mark -- 初始化进度条
//初始化进度条
- (void)initRoundedFatProgressBar
{
    NSArray *tintColors = @[[UIColor colorWithRed:33/255.0f green:180/255.0f blue:162/255.0f alpha:1.0f],
                            [UIColor colorWithRed:3/255.0f green:137/255.0f blue:166/255.0f alpha:1.0f],
                            [UIColor colorWithRed:91/255.0f green:63/255.0f blue:150/255.0f alpha:1.0f],
                            [UIColor colorWithRed:87/255.0f green:26/255.0f blue:70/255.0f alpha:1.0f],
                            [UIColor colorWithRed:126/255.0f green:26/255.0f blue:36/255.0f alpha:1.0f],
                            [UIColor colorWithRed:149/255.0f green:37/255.0f blue:36/255.0f alpha:1.0f],
                            [UIColor colorWithRed:228/255.0f green:69/255.0f blue:39/255.0f alpha:1.0f],
                            [UIColor colorWithRed:245/255.0f green:166/255.0f blue:35/255.0f alpha:1.0f],
                            [UIColor colorWithRed:165/255.0f green:202/255.0f blue:60/255.0f alpha:1.0f],
                            [UIColor colorWithRed:202/255.0f green:217/255.0f blue:54/255.0f alpha:1.0f],
                            [UIColor colorWithRed:111/255.0f green:188/255.0f blue:84/255.0f alpha:1.0f]];
    
    _progressBarRoundedFat.progressTintColors       = tintColors;
    _progressBarRoundedFat.stripesOrientation       = YLProgressBarStripesOrientationLeft;
    _progressBarRoundedFat.indicatorTextDisplayMode = YLProgressBarIndicatorTextDisplayModeProgress;
    _progressBarRoundedFat.indicatorTextLabel.font  = [UIFont fontWithName:@"Arial-BoldMT" size:20];
    _progressBarRoundedFat.progressStretch          = NO;
    [_progressBarRoundedFat setProgress:0.0 animated:NO];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
